<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="选择群" prop="groupId">
        <el-col :span="15">
          <el-form-item prop="groupId">
            <el-select v-model="queryParams.groupId" placeholder="请选择"
                       style="width: 180px" @change="handleQuery">
              <el-option
                  v-for="dict in userGroups"
                  :key="dict.id"
                  :label="dict.groupName"
                  :value="dict.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="时间">
        <el-col :span="15">
          <el-date-picker
              v-model="queryParams.findTime"
              type="daterange"
              @change="handleQuery"
              range-separator="To"
              start-placeholder="Start date"
              end-placeholder="End date"
          />
        </el-col>
      </el-form-item>
      <el-form-item label="用户名称" prop="userName">
        <el-input
            v-model="queryParams.userName"
            placeholder="请输入用户名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="排序" prop="orderByType">
        <el-select v-model="queryParams.orderByType" placeholder="请选择" clearable style="width: 200px"
                   @change="handleQuery">
          <el-option
              v-for="dict in group_find_order"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-checkbox v-model="queryParams.orderByTypeDesc" label="倒序" :true-value=2 :false-value=1
                     @change="handleQuery"/>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">清空</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['group:guRef:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5" v-if="permitUpdate() > 1">
        <el-button
            type="success"
            plain

            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['group:guRef:update']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5" v-if="permitUpdate() > 1">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['group:guRef:deletes']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5" v-if="permitUpdate() > 1">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['group:guRef:export']"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5" v-if="permitUpdate() > 0">
        <el-button
            type="warning"
            plain
            :disabled="ids.length<2"
            @click="merge"
            v-hasPermi="['group:guRef:toMerge']"
        >用户数据合并
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table ref="tableRef" v-loading="loading" :data="refList" @selection-change="handleSelectionChange"
              :row-key="(row)=>{return row.id}">
      <el-table-column type="selection" width="55" align="center" :reserve-selection="true"/>
      <!--      <el-table-column label="id" align="center" prop="id"/>-->
      <!--      <el-table-column label="群id" align="center" prop="groupId"/>-->
      <!--      <el-table-column label="用户id" align="center" prop="userId"/>-->
      <el-table-column v-if="!groupId" label="群名称" align="center" prop="groupName"/>
      <el-table-column label="用户名称" align="center" prop="userName"/>
      <el-table-column label="群角色" align="center" prop="adminType">
        <template #default="scope">
          <dict-tag :options="group_user_role" :value="scope.row.adminType"/>
        </template>
      </el-table-column>
      <el-table-column label="性别" align="center">
        <template #default="scope">
          <dict-tag :options="sys_user_sex" :value="scope.row.sex"/>
        </template>
      </el-table-column>
      <el-table-column label="打水次数" align="center" class-name="small-padding ">
        <template #default="scope">
          <el-button link type="primary" icon="Link" v-hasPermi="['group:boutStat:listPage']"
                     @click="skipPage(scope.row,'/group/boutStat')">
            {{ scope.row.competitionNum }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="活动次数" align="center" class-name="small-padding ">
        <template #default="scope">
          <el-button link type="primary" icon="Link" v-hasPermi="['group:participator:listPage']"
                     @click="skipPage(scope.row,'/group/participator')">
            {{ scope.row.activityNum }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="活动消费" align="center" prop="activityCost"/>
      <el-table-column label="总局数" align="center" prop="totalBout"/>
      <el-table-column label="总胜局数" align="center" prop="winBout"/>
      <el-table-column label="总负局数" align="center" prop="loseBout"/>
      <el-table-column label="总得分" align="center" prop="totalScore"/>
      <el-table-column label="总奖励" align="center" prop="awardCoin"/>
      <el-table-column label="胜率" align="center">
        <template #default="scop">
          {{ Number(scop.row.winRate).toFixed(2) }}%
        </template>
      </el-table-column>
      <el-table-column label="排名" align="center" prop="levelName"/>
      <el-table-column label="让分" align="center" prop="effect"/>
      <!--      <el-table-column label="登录默认群" align="center">-->
      <!--        <template #default="scope">-->
      <!--          <dict-tag :options="group_login_default" :value="scope.row.loginDefault"/>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="入群时间" align="center" prop="createTime" width="120px">
        <template #default="scope">
          {{ format(scope.row.createTime, 'yyyy-MM-dd') }}
        </template>
      </el-table-column>
      <!--      <el-table-column label="租户编号" align="center" prop="tenantId"/>-->
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="updateType=1;allocateRole(scope.row)"
                     v-if="permitUpdate(scope.row.groupId) > 1"
                     v-hasPermi="['group:guRef:setManager']">
            角色分配
          </el-button>
          <el-button link type="primary" icon="Edit" @click="updateType=2;allocateRole(scope.row)"
                     v-if="permitUpdate(scope.row.groupId) && !scope.row.userId"
                     v-hasPermi="['group:guRef:setManager']">
            绑定用户
          </el-button>
          <el-button link type="primary" icon="Edit" @click="setManager(scope.row.id,-1)"
                     v-if="permitUpdate(scope.row.groupId) && scope.row.userId"
                     v-hasPermi="['group:guRef:setManager']">
            解绑用户
          </el-button>
          <el-button link type="primary" icon="Delete" @click="setManager(scope.row.id,-2)"
                     v-if="permitUpdate(scope.row.groupId) "
                     v-hasPermi="['group:guRef:setManager']">删除数据
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
    <!--    合并对话框-->
    <el-dialog :title="title" v-if="mergelist" v-model="mergeDialog" width="800px" append-to-body @close="proxy.$refs['mergeRef'].clearSelection()">
      <el-table ref="mergeRef" v-loading="loading" :data="mergelist" @select="setMergeId"
                :header-cell-class-name="headerCellClassName">
        <el-table-column label="合并到" type="selection" width="55" align="center"/>
        <el-table-column label="用户名称" align="center" prop="userName"/>
        <el-table-column label="群角色" align="center" prop="adminType">
          <template #default="scope">
            <dict-tag :options="group_user_role" :value="scope.row.adminType"/>
          </template>
        </el-table-column>
        <el-table-column label="性别" align="center">
          <template #default="scope">
            <dict-tag :options="sys_user_sex" :value="scope.row.sex"/>
          </template>
        </el-table-column>
        <el-table-column label="打水次数" align="center" prop="competitionNum"/>
        <el-table-column label="活动次数" align="center" prop="activityNum"/>
        <el-table-column label="活动消费" align="center" prop="activityCost"/>
        <el-table-column label="总局数" align="center" prop="totalBout"/>
        <el-table-column label="总胜局数" align="center" prop="winBout"/>
        <el-table-column label="总负局数" align="center" prop="loseBout"/>
        <el-table-column label="总得分" align="center" prop="totalScore"/>
        <el-table-column label="总奖励" align="center" prop="awardCoin"/>
        <el-table-column label="入群时间" align="center" prop="createTime" width="120px">
          <template #default="scope">
            {{ format(scope.row.createTime, 'yyyy-MM-dd') }}
          </template>
        </el-table-column>

      </el-table>
      <el-button  type="primary" @click="toMerge()">合并</el-button>
    </el-dialog>
    <!-- 添加或修改入群申请对话框 -->
    <el-dialog :title="title" v-model="allocateRoleF" width="800px" append-to-body :show-close="false">
      <el-form ref="applyRef" :model="form" label-width="90px">
        <el-form-item label="用户名称">
          <el-input v-model="form.userName" :disabled="form.userName"></el-input>
        </el-form-item>
        <el-form-item v-if="!form.userId && updateType ==2" label="用户邀请码">
          <el-input v-model="form.userCode" placeholder="请输入用户邀请码"></el-input>
        </el-form-item>
        <el-form-item v-if="updateType ==1" label="角色">
          <el-col :span="24">
            <el-form-item>
              <el-radio-group v-model="form.adminType">
                <template v-for="dict in group_user_role" :key="dict.value">
                  <el-radio
                      v-if="dict.value < 2"
                      :value="dict.value"
                  >
                    {{ dict.label }}
                  </el-radio>
                </template>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="setManager">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 添加或修改用户和群关系对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="refRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item v-if="!form.id" label="选择群" prop="groupId">
          <el-col :span="24">
            <el-form-item prop="groupId">
              <el-select v-model="form.groupId" placeholder="请选择" :disabled="form.id>0 || queryParams.groupId>0">
                <el-option
                    v-for="dict in userGroups"
                    :key="dict.id"
                    :label="dict.groupName"
                    :value="dict.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="用户名称" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户名称"/>
        </el-form-item>
        <el-form-item v-if="!form.userId && updateType ==2" label="绑定用户">
          <el-input v-model="form.userCode" placeholder="请输入用户邀请码"></el-input>
        </el-form-item>
        <el-form-item label="默认登录：" prop="loginDefault" label-width="95px">
          <el-form-item>
            <el-col :span="24">
              <el-form-item>
                <el-radio-group v-model="form.loginDefault">
                  <el-radio
                      v-for="dict in group_login_default"
                      :key="dict.value"
                      :value="dict.value"
                  >{{ dict.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-form-item>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Ref">
import * as refServer from "@/api/group/ref.js";
import {AES_Decrypt, AES_Encrypt, decrypt} from "@/utils/jsencrypt.js";
import * as groupServer from "@/api/group/group.js";
import {format} from "date-fns";
import {findByIds} from "@/api/group/ref.js";

const {proxy} = getCurrentInstance();
const {
  sys_user_sex,
  group_login_default,
  group_user_role,
  group_find_order
} = proxy.useDict("sys_user_sex", "group_login_default", "group_user_role", "group_find_order");
const refList = ref([]);
const mergelist = ref([]);
const open = ref(false);
const mergeDialog = ref(false);
const allocateRoleF = ref(false);
const updateType = 1;
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const mergeId = ref({});
const mergeRef = null;
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const resetFlag = ref(false);
const route = useRoute();
const router = useRouter();
const groupId = ref(Number(AES_Decrypt(route.query.groupId)) === 0 ? undefined : Number(AES_Decrypt(route.query.groupId)));
const userGroups = ref([])
const groupPermitMap = reactive(new Map())
const data = reactive({
  form: {},
  queryParams: {
    orderByType: 1,
    orderByTypeDesc: 2,
    pageNum: 1,
    startTime: null,
    findTime: null,
    endTime: null,
    pageSize: 10,
    groupId: groupId.value,
    userId: null,
    userName: null,
    adminType: null,
    sex: null,
    competitionNum: null,
    activityNum: null,
    activityCost: null,
    totalBout: null,
    winBout: null,
    loseBout: null,
    totalScore: null,
    awardCoin: null,
    loginDefault: null,
    tenantId: null,
  },
  rules: {
    groupId: [
      {required: true, message: "群id不能为空", trigger: "blur"}
    ],
    userName: [
      {required: true, message: "用户名称不能为空", trigger: "blur"}
    ],
    adminType: [
      {required: true, message: "0:普通成员,1:管理员,2:群主不能为空", trigger: "change"}
    ],
    sex: [
      {required: true, message: "性别：0女，1男不能为空", trigger: "change"}
    ],
    competitionNum: [
      {required: true, message: "打水次数不能为空", trigger: "blur"}
    ],
    activityNum: [
      {required: true, message: "活动次数不能为空", trigger: "blur"}
    ],
    activityCost: [
      {required: true, message: "活动消费不能为空", trigger: "blur"}
    ],
    totalBout: [
      {required: true, message: "总局数不能为空", trigger: "blur"}
    ],
    winBout: [
      {required: true, message: "总胜局数不能为空", trigger: "blur"}
    ],
    loseBout: [
      {required: true, message: "总负局数不能为空", trigger: "blur"}
    ],
    totalScore: [
      {required: true, message: "总得分不能为空", trigger: "blur"}
    ],
    awardCoin: [
      {required: true, message: "总奖励不能为空", trigger: "blur"}
    ],
    loginDefault: [
      {required: true, message: "默认登录群：0否，1是不能为空", trigger: "blur"}
    ],
    createTime: [
      {required: true, message: "创建时间不能为空", trigger: "blur"}
    ],
    updateTime: [
      {required: true, message: "更新时间不能为空", trigger: "blur"}
    ],
    deleted: [
      {required: true, message: "是否删除不能为空", trigger: "blur"}
    ],
    tenantId: [
      {required: true, message: "租户编号不能为空", trigger: "blur"}
    ],
  }
});

const {queryParams, form, rules} = toRefs(data);

function skipPage(row, path) {
  router.push({path: path, query: {userGroupRefId: AES_Encrypt(row.id), groupId: AES_Encrypt(row.groupId)}});
}

const start = (() => {
  return new Promise(resolve => {
    groupServer.callFindList(null).then(res => {
      userGroups.value = res.data
      userGroups.value.forEach(item => {
        groupPermitMap.set(item.id, item.adminType)
      })
      if (!groupId.value && !resetFlag.value) {
        userGroups.value.forEach(item => {
          if (item.loginDefault === 1) {
            groupId.value = item.id
            queryParams.value.groupId = item.id
          }
        })
      }
      if (!groupId.value && !resetFlag.value) {
        groupId.value = userGroups.value[0].id
        queryParams.value.groupId = userGroups.value[0].id
      }
    }).then(() => {
      // //console.log("start",currentAdmin.value)
      resolve()
    })
  })
})

function permitUpdate(groupId) {
  if(!groupId){
    //console.log(groupId);
    groupId = queryParams.value.groupId
  }
  // //console.log("groupId",groupId);
  // //console.log(groupPermitMap.get(groupId),"groupPermitMap.get(groupId)");
  return groupPermitMap.get(groupId)
}

/** 查询用户和群关系列表 */
function getList() {
  loading.value = true;
  start().then(() => {
    if (queryParams.value.findTime) {
      queryParams.value.endTime = queryParams.value.findTime[1]
      queryParams.value.startTime = queryParams.value.findTime[0]
    }
    refServer.listRef(queryParams.value).then(response => {
      refList.value = response.data.list;
      total.value = response.data.total;
      loading.value = false;
    });
  })
}

// 取消按钮
function cancel() {
  open.value = false;
  allocateRoleF.value = false;
  reset();
}

// 表单清空
function reset() {
  form.value = {
    startTime: null,
    findTime: null,
    endTime: null,
    id: null,
    groupId: groupId.value ? groupId.value : null,
    userId: null,
    userName: null,
    adminType: null,
    sex: null,
    competitionNum: null,
    activityNum: null,
    activityCost: null,
    totalBout: null,
    winBout: null,
    loseBout: null,
    totalScore: null,
    awardCoin: null,
    loginDefault: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    deleted: null,
    tenantId: null,
    remark: null
  };
  proxy.resetForm("refRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 清空按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.groupId = undefined;
  groupId.value = null;
  resetFlag.value = true;
  queryParams.value.startTime = null;
  queryParams.value.findTime = null;
  queryParams.value.endTime = null;
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  // //console.log("selection", selection);
  // //console.log("ids.value",ids.value);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加用户和群关系";
  form.value.groupId = queryParams.value.groupId
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value[0]
  refServer.getRef({id: _id}).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改用户和群关系";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["refRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        refServer.updateRef(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        refServer.addRef(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

function allocateRole(row) {
  form.value = {...row}
  allocateRoleF.value = true;
}

//成员角色分配
const setManager = (id, adminType) => {
  let con = true
  let item = form.value
  if (adminType) {
    item.adminType = adminType
    item.id = id
  }
  if (item.adminType == 2) {
    con = confirm("确定将该用户设置为群主吗？")
  }
  if (item.adminType == -1) {
    con = confirm("确定将该用户踢出该群吗？")
    item.deleted = -1
  }
  if (item.adminType == -2) {
    con = confirm("删除本条数据？")
    item.deleted = -2
  }
  // if (!item.userCode) {
  //   item.setMember = !item.setMember
  // }
  if (con) {
    refServer.setManager({
      userCode: item.userCode,
      id: item.id,
      adminType: item.adminType,
      deleted: item.deleted,
    }).then(res => {
      if (res) {
        allocateRoleF.value = false;
        getList()
        reset();
      }
    })
  }
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id ? [row.id] : ids.value;
  proxy.$modal.confirm('是否确认删除用户和群关系编号为"' + _ids + '"的数据项？').then(function () {
    return refServer.delRef({delIds: _ids});
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

function merge() {
  const _ids = ids.value;
  mergeDialog.value = true;
  refServer.findByIds({findIds: _ids}).then(response => {
    mergelist.value = response.data
  })
}

// function setMergeId(selection) {
//   if (selection.length > 0) {
//     mergeId.value.push( selection[0].id);
//   }else {
//     mergeId.value = [];
//   }
//   //console.log(mergeId.value.length);
// }

function setMergeId(selection, row) {
  if (mergeId.value && mergeId.value.id === row.id) {
    proxy.$refs["mergeRef"].clearSelection()
    mergeId.value = null
    return
  }
  proxy.$refs["mergeRef"].clearSelection()
  proxy.$refs["mergeRef"].toggleRowSelection(row)
  mergeId.value = row
  // //console.log(mergeId.value);
}

function headerCellClassName({row, column, rowIndex, columnIndex}) {
  if (columnIndex === 0) {
    return 'seltAllbtnDis'
  }
}

function toMerge() {
  const _ids = ids.value;
  // //console.log(mergeId.value);
  refServer.toMerge({findIds: _ids, id: mergeId.value.id}).then(response => {
    ids.value = []
    mergeId.value = []
    mergelist.value = [];
    mergeDialog.value = false;
    proxy.$modal.msgSuccess("合并成功");
    proxy.$refs["tableRef"].clearSelection()
    proxy.$refs["mergeRef"].clearSelection()
    getList();
  })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('group/ref/export', {
    ...queryParams.value
  }, `ref_${new Date().getTime()}.xlsx`)
}

getList()
</script>
<style lang="scss" scoped>
::v-deep .seltAllbtnDis .cell {
  visibility: hidden;
}

</style>
